﻿using AppEvents;
using AppEvents.JsonModel;
using MebApp.Launcher.Helpers;
using MebApp.Launcher.Model;
using MebApp.Launcher.Views;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TinyUtil;

namespace MebApp.Launcher
{
    public partial class FormMain : BaseForm
    {
        LoginViewModel userVm;
        Dictionary<Guid, AppInfomationPanel> infoPanels = new Dictionary<Guid, AppInfomationPanel>();
        List<AppEvents.JsonModel.AppJson> appList = new List<AppEvents.JsonModel.AppJson>();
        public Guid LaunchAppId = Guid.Empty;
        public FormMain(Guid launchAppId)
        {
            LaunchAppId = launchAppId;
            InitializeComponent();
            this.CenterScreenOrParent();
            tabControl1.SelectedIndexChanged += TabControl1_SelectedIndexChanged;
            TabPage page = tabControl1.TabPages["allApps"];
            page.ContextMenuStrip = contextMenuStrip2;
            ShortcutLaunchListener.StartListen((appId) =>
            {
                if (appId == Guid.Empty)
                    return;
                LaunchAppId = appId;
                LoadAppApps();
            });
        }

        private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var page = tabControl1.TabPages[tabControl1.SelectedIndex];
            if (page.Name == "allApps")
            {
                LoadAppApps();
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            Helpers.ShortcutHelper.AddShortcut(Guid.Empty, "MebApp启动器", Application.ExecutablePath);
            if (new FormLogin().ShowDialog(this) == DialogResult.OK)
            {
                userVm = base.ReadModel<LoginViewModel>();
                自动登录ToolStripMenuItem.Checked = userVm.AutoLogin;
                自动登录ToolStripMenuItem.Click += 自动登录ToolStripMenuItem_CheckedChanged;
                LoadAppApps();
            }
            else
            {
                Environment.Exit(0);
            }
        }

        private void LoadAppApps()
        {
            AppJson launchAppJson = null;
            Button launchButton = null;
            var resp = LauncherApp.AppClient.GetApps(null, 1, 1);
            if (resp != null)
            {
                if (resp.code == 200)
                {
                    appList = resp.As<List<AppEvents.JsonModel.AppJson>>();
                    TabPage page = tabControl1.TabPages["allApps"];
                    if (page.Controls.Count == 0)
                    {
                        page.Controls.Add(new FlowLayoutPanel() { Dock = DockStyle.Fill });
                    }
                    var panel = (page.Controls[0] as FlowLayoutPanel);
                    panel.Controls.Clear();
                    foreach (var item in appList)
                    {
                        var btn = new Button();
                        var g = btn.CreateGraphics();
                        btn.Text = item.Name;
                        btn.Height = 30;
                        btn.Width = (int)g.MeasureString(item.Name, btn.Font).Width + 20;
                        btn.Tag = item;
                        btn.Click += Btn_Click;
                        if (item.ID == LaunchAppId)
                        {
                            launchAppJson = item;
                            launchButton = btn;
                        }
                        panel.Controls.Add(btn);
                    }
                    if (launchButton != null)
                    {
                        Btn_Click(launchButton, EventArgs.Empty);
                        infoPanels[launchAppJson.ID].RunApp();
                        LaunchAppId = Guid.Empty;
                        this.WindowState = FormWindowState.Minimized;
                    }
                }
                else
                {
                    this.MessageBoxShow(resp.msg);
                }
            }
        }

        private void 自动登录ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            自动登录ToolStripMenuItem.Checked = !自动登录ToolStripMenuItem.Checked;
            userVm.AutoLogin = 自动登录ToolStripMenuItem.Checked;
            WriteModel(userVm);
        }

        private void Btn_Click(object sender, EventArgs e)
        {
            lock (infoPanels)
            {
                var info = (sender as Control).Tag as AppJson;
                this.InfopanelContainer.Controls.Clear();
                if (!infoPanels.ContainsKey(info.ID))
                {
                    infoPanels.Add(info.ID, new AppInfomationPanel() { Dock = DockStyle.Fill });
                }
                this.InfopanelContainer.Controls.Add(infoPanels[info.ID]);
                infoPanels[info.ID].SetAppInfo(info);
                var resp = LauncherApp.AppClient.GetUserApp(info.ID);
                if (resp != null && resp.code == 200)
                {
                    var userApp = resp.As<UserApp>();
                    infoPanels[info.ID].SetUserApp(userApp);
                }
            }
        }

        private void 上传应用ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new Views.FormUploadApp().ShowDialog(this);
        }

        //private void 测试应用程序域启动AppToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    var option = new AppLoadOption();
        //    option.appName = "MarketplaceAppSample";
        //    option.appId = "1";
        //    option.path = @"C:\Users\linswin\Documents\Visual Studio 2015\Projects\AppEvents\MarketplaceAppSample\bin\Debug";
        //    option.instanceId = "1";
        //    option.sessionId = "1";
        //    option.appVersion = "1";
        //    option.userId = "1";
        //    option.assemblyName = "MarketplaceAppSample";
        //    option.startupClass = "MarketplaceAppSample.AppSample";
        //    AppLoader.LoadApp(option);
        //}

        private void buttonCheckUpdate_Click(object sender, EventArgs e)
        {
            var installed = AppInstaller.GetInstalledApps();
            if (!installed.Any())
            {
                this.MessageBoxShow("你还没有安装任何的应用呢！");
                return;
            }
            var checkList = installed.Select(x => new UpdateCheckItem() { ID = x.ID, Version = x.Version }).ToList();
            var resp = LauncherApp.AppClient.GetAppUpdates(checkList);
            if (resp != null && resp.code == 200)
            {
                var uplist = resp.As<List<AppJson>>();
                if (!uplist.Any())
                {
                    this.MessageBoxShow("你的应用都是最新版本呢！(其实我根本就没检查...)");
                }
                else
                {

                }
            }
        }

        //SEARCH
        private void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.textBox1.Text))
            {
                var resp = LauncherApp.AppClient.GetApps(this.textBox1.Text, 1, 1);
                if (resp != null)
                {
                    if (resp.code == 200)
                    {
                        appList = resp.As<List<AppEvents.JsonModel.AppJson>>();
                        TabPage page = tabControl1.TabPages["searchResult"];
                        if (page.Controls.Count == 0)
                        {
                            page.Controls.Add(new FlowLayoutPanel() { Dock = DockStyle.Fill });
                        }
                        var panel = (page.Controls[0] as FlowLayoutPanel);
                        panel.Controls.Clear();
                        foreach (var item in appList)
                        {
                            var btn = new Button()
                            {
                                Text = item.Name,
                                Height = 30,
                                Width = 70,
                                Tag = item
                            };
                            btn.Click += Btn_Click;
                            panel.Controls.Add(btn);
                        }
                        tabControl1.SelectedTab = page;
                    }
                    else
                    {
                        this.MessageBoxShow(resp.msg);
                    }
                }
            }

        }

        private void cRMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UnderDevelopment();
        }

        private void oA公告ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UnderDevelopment();
        }

        private void 邮件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UnderDevelopment();
        }

        private void UnderDevelopment()
        {
            this.MessageBoxShow("开发中");
        }

        private void 企业邮箱ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.DialogShow<FormMailServerSelect>();
        }

        private void 办公OAToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://oa.meierbei.com");
        }

        private void cRMToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Process.Start("http://crm.meierbei.com");
        }

        private void 美呗官网ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("https://www.meb.com/");
        }

        private void 美呗后台ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://admin.meb.com");
        }

        private void 退出ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void 检查启动器更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var xml = TinyUtil.XmlFile.Read<AppUpdateInfo>("update.xml");
            if (TinyUtil.UpdateUtil.HasNewVersion(ref xml))
            {
                this.MessageBoxShow("发现新版本，下次启动时将升级！");
            }
            else
            {
                this.MessageBoxShow("应用启动器已是最新版本！");
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void 使用统计ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UnderDevelopment();
        }

        private void 开机启动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.UnderDevelopment();
        }

        private void 自动更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UnderDevelopment();
        }

        private void 应用程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UnderDevelopment();
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadAppApps();
        }
    }
}
